<html>
  <body>
<h3><a href="http://steve-yegge.blogspot.com/2008/01/emergency-elisp.html">Emergency
Elisp</a><div class="lastUpdated">12/24/2008 08:02 PM</div></h3>
<div xml:base="http://steve-yegge.blogspot.com/atom.xml" class="feedEntryContent">Are
 you an Emacs user but don't know Lisp?  Welcome to my first Emacs Lisp 
primer!  This should hopefully help get you over the hurdle so you can 
have more control over your Emacs sessions.<br /><br />There are lots of
 ways to do things in Lisp, and some are "Lispier" than others.  I'm 
going to focus on how to do things you probably already know how to do 
from C++ or Java.<br /><br />I'm mostly focusing on the language itself,
 since that's arguably the hardest part.  There are tons of 
Emacs-specific APIs that you can learn how to use from the 
documentation.<br /><br />Lisp is good at some things (like code that 
generates code) and not so good at others (like arithmetic expressions).
  I will generally avoid talking about good vs. bad, and just talk about
 how to do things.  Emacs Lisp is like any other language – you get used
 to it eventually.<br /><br />Most Lisp introductions try to give you 
the "Tao of Lisp", complete with incense-burning, chanting, yoga and all
 that stuff.  What I really wanted in the beginning was a simple 
cookbook for doing my "normal" stuff in Lisp.  So that's what this is.  
It's an introduction to how to write C, Java or JavaScript code in Emacs
 Lisp, more or less.<br /><br />Here goes.  Let's see how short I can 
make it.  I'll start with the boring (but hopefully familiar) lexical 
tokens and operators, then move on to how to implement various favorite 
statements, declarations and other programming constructs.<br /><br /><b>Quick Start</b><br /><br />Lisp is written as nested parenthesized expressions like <code>(+ 2 3)</code>.  These expressions are sometimes called <em>forms</em> (in the sense of "shapes".)<br /><br />There
 are also "atoms" (leaf nodes, basically) that are not parenthesized:  
strings, numbers, symbols (which must be quoted with apostrophe for use 
as symbols, like <code>'foo</code>), vectors, and other miscellany.<br /><br />There are only single-line comments:  semicolon to end of line.<br /><br />To set a variable named <code>foo</code> to the value "bar":<br /><pre>(setq foo "bar")  <span class="comment">; setq means "set quoted"</span></pre><br />To call a function named <code>foo-bar</code> with arguments "flim" and "flam":<br /><pre>(foo-bar "flim" "flam")</pre><br />To compute the arithmetic expression (0x15 * (8.2 + (7 &lt;&lt; 3))) % 2:<br /><pre>(% (* #x15 (+ 8.2 (lsh 7 3))) 2)</pre><br />In other words, arithmetic uses prefix notation, just like lisp function calls.<br /><br />There's
 no static type system; you use runtime predicates to figure out the 
type of a data item.  In elisp, predicate functions often end with "p". 
 I'll let you figure out what it stands for.<br /><br /><em>Important:</em>  You can (and should) experiment with Lisp in the <code>*scratch*</code> buffer.  You can evaluate an expression and see its result in any of several ways, including:<br /><ol><br />  <li>Put your cursor after the last close-paren and type <code>C-j</code> (control + j)</li><br />  <li>Put your cursor inside the expression and type <code>M-C-x</code> (alt + control + x)</li><br />  <li>Put your cursor after the last close-paren and type <code>C-x C-e</code></li>       <br /></ol><br />The first approach spits the result into the <code>*scratch*</code>
 buffer, and the next two echo it into the minibuffer.  They all also 
work for atoms – expressions not in parens such as numbers, strings, 
characters and symbols.<br /><h2>Lexical Stuff</h2><br />Lisp has only a handful of lexical tokens (i.e. atomic program elements).<br /><br /><b>Comments</b>:<br /><br />Single-line only.  They start with a semicolon:<br /><pre>(blah blah blah)   ;  I am a comment</pre><br /><b>Strings</b>:<br /><br />Double-quoted only.<br /><pre>"He's said: \"Emacs Rules\" one time too many."</pre><br />You can embed newlines in strings, like so:<br /><pre>"Oh Argentina!<br />Your little tin of pink meat<br />Soars o'er the Pampas"</pre><br /><b>Characters</b>:<br /><ul><br />  <li>?x is the syntax for an ASCII character:  ? followed by the character.</li><br />  <li>e.g.:  ?a is ascii 97 ('a'), ? (that is, question-mark space) is ascii 32 (' ').</li><br />  <li>Some need to be escaped, such as ?\(, ?\) and ?\\</li><br />  <li>Emacs 22+ has unicode support.  Out of scope for this primer.</li><br /></ul>
 Characters are just int values internally, so you can use arithmetic 
operations on them (for instance, to iterate through ?a to ?z).<br /><br /><b>Numbers</b>:<br /><ul><br />  <li>Integers are 29 bits of precision (not the usual 32).  <code>-32, 0, 157</code>, etc.</li><br />  <li>Binary:  start with #b, e.g. <code>#b10010110</code></li><br />  <li>Octal:  #o[0-7]+,  e.g. <code>#o377</code></li><br />  <li>Hexadecimal:  start with #x, e.g. <code>#xabcd, #xDEADBEE</code></li><br />  <li>Floating-point:  the usual.  <code>-10.005, 0.0, 3.14159265</code>  (64 bits of precision.)</li><br />  <li>Scientific:  the usual.  <code>6.02e23</code>, <code>5e-10</code></li><br /></ul><br />The variables <code>most-positive-fixnum</code> and <code>most-negative-fixnum</code>
 are the largest and smallest integers representable in Emacs Lisp 
without bignum support.  Emacs 22+ comes with a fancy bignum/math 
library called <code>calc</code>, if you need it.  Arithmetic operations overflow and underflow the way you'd expect (in, say, C or Java.)<br /><br /><b>Booleans</b><br /><br />The symbol <code>t</code> (just a letter 't' by itself) is <code>true</code>.<br /><br />The symbol <code>nil</code> is <code>false</code> (and also means <code>null</code>).<br /><br />In Emacs Lisp, <code>nil</code> is the only false value; everything else evalutes to <code>true</code>
 in a boolean context, including empty strings, zero, the symbol 'false,
 and empty vectors.  An empty list, '(), is the same thing as <code>nil</code>.<br /><br /><b>Arrays</b><br /><br />Elisp
 has fixed-sized arrays called "vectors".  You can use square-brackets 
to create a pre-initialized literal vector, for instance:<br /><pre>[-2 0 2 4 6 8 10]<br />["No" "Sir" "I" "am" "a" "real" "horse"]<br />["hi" 22 120 89.6 2748 [3 "a"]]</pre><br />Note that you do not (and cannot) use commas to separate the elements; use whitespace.<br /><br />Vectors can have mixed-type elements, and can be nested.  You usually use the function <code>make-vector</code> to create them, since literal vectors are singletons, which can be surprising.<br /><br /><b>Lists</b><br /><br />Lisp
 makes heavy use of linked lists, so there's lexical syntax for them.  
Anything in parentheses is a list, but unless you quote it, it will be 
evaluated as a function call.  There are various ways to quote things in
 Lisp:<br /><pre>(quote (1 2 3)) ; produces the list (1 2 3) with no list-element evaluation</pre><pre>'(1 2 3)  ; apostrophe is shorthand for (quote (...))<br />          ; note that it goes _outside_ the left-paren</pre><pre>(list 1 (+ 1 1) 3) ; also produces (1 2 3), since it evaluates the elements first</pre><pre>`(1 ,(+ 1 1) 3)  ; another (1 2 3) via a template system called "backquote"</pre>There's a lot more that could be said about lists, but other people have already said it.<br /><br /><b>Pairs</b><br /><br />You can set the head and tail (also known as <code>car</code> and <code>cdr</code>) fields of a lisp link-list node struct (also known as a <code>cons</code> cell) directly, using it as a 2-element untyped struct.  The syntax is <code>(head-value . tail-value)</code>, and you have to quote it (see above).<br /><br />A common lookup-table data-structure for very small data sets is an associative list (known as an <code>alist</code>).  It's just a list of dotted pairs, like so:<br /><pre>'( (apple . "red")<br />   (banana . "yellow")<br />   (orange . "orange") )</pre>
 Emacs Lisp has built-in hashtables, bit-vectors, and miscellaneous 
other data structures, but there's no syntax for them; you create them 
with function calls.<br /><h2>Operators</h2><br />Some operations that are typically operators in other languages are function calls in elisp.<br /><br /><b>Equality</b><br /><br />Numeric equality:  <code>(= 2 (+ 1 1))</code>  Single-equal.  Yields <code>t</code> or <code>nil</code>.  Works for floats too.<br /><br />Not-numerically-equal:  <code>(/= 2 3)</code>  I know, it looks like assign-divide-equal.  But it's not.<br /><br />Value equality: <code>(eq 'foo 2)</code>  Like Java ==.  Works for ints, symbols, interned strings, and object references.  Use <code>eql</code> for floating-point numbers (or just <code>=</code>).<br /><br />Deep (structural) equality: use <code>equal</code>, as in:<br /><pre>(equal '(1 2 (3 4)) (list 1 2 (list 3 (* 2 2))))  ; true</pre><br />The equal function is like Java's <code>Object.equals()</code>. Works for lists, vectors, strings, and just about anything else.<br /><br /><b>String</b><br /><br />Strings don't have any operators, but there are lots of string functions.  Some common ones:<br /><pre>(concat "foo" "bar" "baz")  ; yields "foobarbaz"<br /><br />(string= "foo" "baz")  ; yields nil (false).  Can also use <code>equal</code>.<br /><br />(substring "foobar" 0 3) ; yields "foo"<br /><br />(upcase "foobar")  ; yields "FOOBAR"</pre><br />Do <code>M-x apropos RET \bstring\b RET</code> to see a list of functions related to strings.<br /><br /><b>Arithmetic</b><br /><br />Easiest to show as a table...<br /><table border="1"><br />  <tr>    <th>C/Java/JS Operator</th>    <th>Emacs Lisp</th>    <th>Example</th>    <th>Result</th>  </tr>  <tr>    <td>+</td>    <td>+</td>    <td>(+ 1 2 3 4 5)</td>    <td>15</td>  </tr>  <tr>    <td>-</td>    <td>-</td>    <td>(- 6 2 3)</td>    <td>1</td>  </tr>  <tr>    <td>*</td>    <td>*</td>    <td>(* 2 -1 4.2)</td>    <td>-8.4</td>  </tr>  <tr>    <td>/</td>    <td>/</td>    <td>(/ 10 3)</td>    <td>3 (use floats for float div)</td>  </tr>  <tr>    <td>%</td>    <td>%</td>    <td>(% 10 2)</td>    <td>0</td>  </tr>  <tr>    <td>&lt;&lt;</td>    <td>lsh</td>    <td>(lsh 1 5)</td>    <td>32</td>  </tr>  <tr>    <td>&gt;&gt;</td>    <td>ash (negative amount)</td>    <td>(ash -32 -4)</td>    <td>-2</td>  </tr>  <tr>    <td>&gt;&gt;&gt;</td>    <td>lsh (negative amount)</td>    <td>(lsh 32 -4)</td>    <td>2</td>  </tr>  <tr>    <td>++</td>    <td>incf (requires 'cl library)</td>    <td>(incf x 6)</td>    <td>x+6</td>  </tr>  <tr>    <td>--</td>    <td>decf (ditto)</td>    <td>(decf x 5)</td>    <td>x-5</td>  </tr>  <tr>    <td>? : (ternary)</td>    <td>(if <em>test-expr then-expr else-expr</em>)</td>    <td>(if t 3 4)</td>    <td>3</td>  </tr>  <tr>    <td>&amp;&amp;</td>    <td>and</td>    <td>(and t t t nil)</td>    <td>nil</td>  </tr>  <tr>    <td>||</td>    <td>or</td>    <td>(or nil nil nil t)</td>    <td>t</td>  </tr>  <tr>    <td>! (logical-not)</td>    <td>not</td>    <td>(not 3)</td>    <td>nil</td>  </tr>  <tr>    <td>~ (bit-not)</td>    <td>lognot</td>    <td>(lognot #b1001)</td>    <td>-10</td>  </tr>  <tr>    <td>^ (bit-xor)</td>    <td>logxor</td>    <td>(logxor 5 3)</td>    <td>6</td>  </tr>  <tr>    <td>&amp; (bit-and)</td>    <td>logand</td>    <td>(logand 1 3)</td>    <td>1</td>  </tr>  <tr>    <td>| (bit-or)</td>    <td>logior</td>    <td>(logior 1 3)</td>    <td>3</td>  </tr>  <tr>    <td>&lt;</td>    <td>&lt;</td>    <td>(&lt; 5 3)</td>    <td>nil</td>  </tr>  <tr>    <td>&gt;</td>    <td>&gt;</td>    <td>(&gt; 5 3)</td>    <td>t</td>  </tr>  <tr>    <td>&lt;=</td>    <td>&lt;=</td>    <td>(&lt;= 3 3)</td>    <td>t</td>  </tr>  <tr>    <td>&gt;=</td>    <td>&gt;=</td>    <td>(&gt;= 5 3)</td>    <td>t</td>  </tr>  <tr>    <td>. (field access)</td>    <td><em>see setf below</em></td>    <td>n/a</td>    <td>n/a</td>  </tr>  <tr>    <td>[] (array access)</td>    <td>aref/aset</td>    <td>(aref [2 4 6] 1)</td>    <td>4</td>  </tr></table><br /><h2>Statements</h2><br />This section has some recipes for simple Java-like statements.  It's not comprehensive – just some recipes to get you going.<br /><br /><b>if/else</b><br /><br /><em>Case 1:  no else clause</em>:  (if <em>test-expr</em> <em>expr</em>)<br /><br />Example:<br /><pre>(if (&gt;= 3 2)<br />  (message "hello there"))</pre><br /><em>Case 2:  else clause</em>:  (if <em>test-expr</em> <em>then-expr</em> <em>else-expr</em>)<br /><pre>(if (today-is-friday)         ; test-expr<br />    (message "yay, friday")   ; then-expr<br />  (message "boo, other day")) ; else-expr</pre>  <br />If you need multiple expressions (statements) in the <em>then-expr</em>, you wrap them with a call to <code>progn</code>, which is like curly-braces in C or Java:<br /><pre>(if (zerop 0)<br />    (progn<br />      (do-something)<br />      (do-something-else)<br />      (etc-etc-etc)))</pre><br />You don't need the <code>progn</code> around the <em>else-expr</em> – everything after the <em>then-expr</em> is considered to be part of the <em>else-expr</em>.  Hence:<br /><pre>(if (today-is-friday)<br />    (message "yay, friday")<br />  (message "not friday!")<br />  (non-friday-stuff)<br />  (more-non-friday-stuff))</pre><br /><em>Case 3:  else-if clause</em>:  Just nest 'em.  Or use <code>cond</code> (see below).<br /><pre>(if 'sunday<br />    (message "sunday!")      ; then-expr<br />  (if 'saturday              ; else-if<br />      (message "saturday!")  ; next then-expr<br />    (message ("weekday!")))) ; final else</pre><br /><em>Case 4:  no else-if, multiple body expressions</em> – use <code>when</code>:<br /><br />If you don't have an <em>else</em>-clause, then you can use the <code>when</code> macro, which provides an implicit <code>progn</code>:<br /><pre>(when (&gt; 5 1)<br />  (blah)<br />  (blah-blah)<br />  (blah blah blah))</pre><br />You can also use <code>unless</code>, which is like <code>when</code> but inverts the sense of the test:<br /><pre>(unless (weekend-p)<br />  (message "another day at work")<br />  (get-back-to-work))</pre><br /><b>switch</b><br /><br />Elisp has two versions of the classic <code>switch</code> statement:  <code>cond</code> and <code>case</code>.<br /><br />Elisp does not have a table-lookup optimization for switch, so <code>cond</code> and <code>case</code>
 are just syntax for nested if-then-else clauses.  However, if you have 
more than one level of nesting, it looks a lot nicer than <code>if</code> expressions.  The syntax is:<br /><pre>(cond<br />  (test-1<br />    do-stuff-1)<br />  (test-2<br />    do-stuff-2)<br />  ...<br />  (t<br />    do-default-stuff))</pre><br />The <code>do-stuff</code> parts can be any number of statements, and don't need to be wrapped with a <code>progn</code> block.<br /><br />Unlike classic <code>switch</code>, <code>cond</code>
 can handle any test expression (it just checks them in order), not just
 numbers.  The downside is that it doesn't have any special-casing for 
numbers, so you have to compare them to something.  Here's one that does
 string compares:<br /><pre>(cond<br /> ((equal value "foo")  ; case #1 – notice it's a function call to `equal' so it's in parens<br />  (message "got foo")  ; action 1<br />  (+ 2 2))             ; return value for case 1<br /> ((equal value "bar")  ; case #2 – also a function call (to `+')<br />  nil)                 ; return value for case 2<br /> (t                    ; default case – not a function call, just literal true<br />  'hello))             ; return symbol 'hello</pre><br />The final <code>t</code> default clause is optional.  The first matching clause is executed, and the result of the entire <code>cond</code> expression is the result of the last expression in the matching clause.<br /><br />The 'cl (Common Lisp) package bundled with Emacs provides <code>case</code>, which works if you're comparing numbers or symbols, so in a sense it works more like standard <code>switch</code>.  Example:<br /><pre>(case 12<br />  (5 "five")<br />  (1 "one")<br />  (12 "twelve")<br />  (otherwise<br />   "I only know five, one and twelve."))  ; result:  "twelve"</pre><br />With <code>case</code> you can use either <code>t</code> or <code>otherwise</code> for the default case, but it must come last.<br /><br />It's cleaner to use <code>case</code> when you can get away with it, but <code>cond</code> is more general.<br /><br /><b>while</b><br /><br />Elisp has a relatively normal <code>while</code> function:  (while <em>test</em> <em>body-forms</em>)<br /><br />Example, which you can evaluate in your <code>*scratch*</code> buffer:<br /><pre>(setq x 10<br />      total 0)<br />(while (plusp x)  ; while x is positive<br />  (incf total x)  ; add x to total<br />  (decf x))       ; subtract 1 from x</pre><br />First we set two global variables, <code>x=10</code> and <code>total=0</code>, then run the loop.  Then we can evaluate the expression <code>total</code> to see that its value is 55 (the sum of the numbers 1 to 10).<br /><br /><b>break/continue</b><br /><br />Lisp has a facility for upward control-flow transfers called <code>catch/throw</code>.  It's very similar to Java or C++ exception handling, albeit possibly somewhat lighter-weight.<br /><br />To do a <code>break</code> from inside a loop in elisp, you put a <code>(catch 'break ...)</code> outside the loop, and a <code>(throw 'break <em>value</em>)</code> wherever you want to break inside the loop, like so:<br /><table cellspacing="3" cellpadding="3" border="1"><br />  <tr>    <th>Emacs Lisp</th>    <th>Java</th>  </tr><tr><td><br /><pre>(setq x 0 total 0)<br />(catch 'break<br />  (while t<br />    (incf total x)<br />    (if (&gt; (incf x) 10)<br />        (throw 'break total))))</pre></td><td><pre>var x = total = 0;<br />while (true) {<br />  total += x;<br />  if (x++ &gt; 10) {<br />    break;<br />  }<br />}</pre></td></tr></table><br />The symbol <code>'break</code> is arbitrary, but is probably a nice choice for your readers.  If you have nested loops, you might consider <code>'break-outer</code> and <code>'break-inner</code> in your <code>catch</code> expressions.<br /><br />You can <code>(throw 'break nil)</code> if you don't care about the "return value" for the <code>while</code>-loop.<br /><br />To <code>continue</code> a loop, put a <code>catch</code>
 expression just inside the loop, at the top.  For instance, to sum the 
numbers from 1 to 99 that are not evenly divisible by 5 (artificially 
lame example demonstrating use of <code>continue</code>):<br /><table cellspacing="3" cellpadding="3" border="1"><br />  <tr>    <th>Emacs Lisp</th>    <th>Java</th>  </tr><tr><td><pre>(setq x 0 total 0)<br />(while (&lt; x 100)<br />  (catch 'continue<br />    (incf x)<br />    (if (zerop (% x 5))<br />        (throw 'continue nil))<br />    (incf total x)))</pre></td><td><pre>var x = total = 0;<br />while (x &lt; 100) {<br />  x++;<br />  if (x % 5 == 0) {<br />    continue;<br />  }<br />  total += x;<br />}</pre></td></tr></table><br />We can combine these examples to show using a break and continue in the same loop:<br /><table cellspacing="3" cellpadding="3" border="1"><br />  <tr>    <th>Emacs Lisp</th>    <th>JavaScript</th>  </tr><tr><td><pre>(setq x 0 total 0)<br />(catch 'break<br />  (while t<br />    (catch 'continue<br />      (incf x)<br />      (if (&gt;= x 100)<br />          (throw 'break nil))<br />      (if (zerop (% x 5))<br />          (throw 'continue nil))<br />      (incf total x))))</pre></td><td><pre>var x = total = 0;<br />while (true) {<br />  x++;<br />  if (x &gt;= 100) {<br />    break;<br />  }<br />  if (x % 5 == 0) {<br />    continue;<br />  }<br />  total += x;<br />}</pre></td></tr></table><br />All the loops above compute the value 4000 in the variable <code>total</code>.  There are better ways to compute this result, but I needed something simple to illustrate <code>break</code> and <code>continue</code>.<br /><br />The <code>catch/throw</code>
 mechanism can be used across function boundaries, just like exceptions.
  It's not intended for true exceptions or error conditions – Emacs has 
another mechanism for that, discussed in the <code>try/catch</code> section below.  You should get comfortable using <code>catch/throw</code> for normal jumps and control transfer in your Elisp code.<br /><br /><b>do/while</b><br /><br />Pretty much all iteration in Emacs Lisp is easiest using the <code>loop</code> macro from the Common Lisp package.  Just do this to enable <code>loop</code>:<br /><pre>(require 'cl)  ; get lots of Common Lisp goodies</pre><br />The <code>loop</code>
 macro is a powerful minilanguage with lots of features, and it's worth 
reading up on.  I'll use it in this primer to show you how to do basic 
looping constructs from other languages.<br /><br />You can do a <code>do/while</code> like so:<br /><pre>(loop do<br />      (setq x (1+ x))<br />      while<br />      (&lt; x 10))</pre><br />You can have any number of lisp expressions between the <code>do</code> and <code>while</code> keywords.<br /><br /><b>for</b><br /><br />The C-style <code>for</code>-loop
 has four components:  variable initialization, the loop body, the test,
 and the increment.  You can do all that and more with the <code>loop</code> macro.  For instance, this arbitrary JavaScript:<br /><pre>// JavaScript<br />var result = [];<br />for (var i = 10, j = 0; j &lt;= 10; i--, j += 2) {<br />  result.push(i+j);<br />}</pre><br />Could be done with <code>loop</code> like so:<br /><pre>(loop with result = '()         ; one-time initialization<br />      for i downfrom 10         ; count i down from 10<br />      for j from 0 by 2         ; count j up from 0 by 2<br />      while (&lt; j 10)            ; stop when j &gt;= 10<br />      do<br />      (push (+ i j) result)     ; fast-accumulate i+j<br />      finally<br />      return (nreverse result)) ; reverse and return result</pre><br />It's a bit more verbose, but <code>loop</code> has a <em>lot</em> of options, so you want it to be reasonably transparent.<br /><br />Notice that this <code>loop</code>
 declares the result array and then "returns" it.  It could also operate
 on a variable declared outside the loop, in which case we wouldn't need
 the <code>finally return</code> clause.<br /><br />The <code>loop</code> macro is astoundingly flexible.  Its full specification is <em>way</em>
 out of scope for this primer, but if you want to make Emacs Lisp your, 
uh, friend, then you should spend some time reading up on <code>loop</code>.<br /><br /><b>for..in</b><br /><br />If you're iterating over a collection, Java provides the "smart" for-loop, and JavaScript has <code>for..in</code> and <code>for each..in</code>.  There are various ways to do it in Lisp, but you really might as well just learn how to do it with the <code>loop</code> macro.  It's a one-stop shop for iteration.<br /><br />The basic approach is to use <code>loop <em>for</em> var <em>in</em> sequence</code>,
 and then do something with the individual results.  You can, for 
instance, collect them (or a function on them) into a result list like 
so:<br /><pre>(loop for i in '(1 2 3 4 5 6)<br />      collect (* i i))           ; yields (1 4 9 16 25 36)</pre><br />The <code>loop</code>
 macro lets you iterate over list elements, list cells, vectors, 
hash-keys, hash-values, buffers, windows, frames, symbols, and just 
about anything else you could want to traverse.  See the Info pages or 
your Emacs manual for details.<br /><br /><b>functions</b><br /><br />You <b>de</b>fine a <b>fun</b>ction with <code>defun</code>.<br /><br />Syntax:  (defun <em>function-name</em> <em>arg-list</em> [<em>optional docstring</em>] <em>body</em>)<br /><pre>(defun square (x)<br />  "Return X squared."<br />  (* x x))</pre><br />For a no-arg function, you use an empty list:<br /><pre>(defun hello ()<br />  "Print the string `hello' to the minibuffer."<br />  (message "hello!"))</pre><br />The <em>body</em>
 can be any number of expressions.  The return value of the function is 
the result of the last expression executed.  You do not declare the 
return type, so it's useful to mention it in the documentation string.  
The doc string is available from <code>M-x describe-function</code> after you evaluate your function.<br /><br />Emacs
 Lisp does not have function/method overloading, but it supports 
optional and "rest" parameters similar to what Python and Ruby offer.  
You can use the full Common Lisp specification for argument lists, 
including support for keyword arguments (see the <code>defstruct</code> section below), if you use the <code>defun*</code> macro instead of <code>defun</code>.  The <code>defun*</code> version also lets you <code>(return "foo")</code> without having to set up your own <code>catch/throw</code>.<br /><br />If you want your function to be available as a <code>M-x</code> command, put <code>(interactive)</code> as the first expression in the body after the doc string.<br /><br /><b>local variables</b><br /><br />You declare function local variables with the <code>let</code> form.  The basic syntax is <code>(let <em>var-decl</em> <em>var-decl</em>)</code><br /><pre><br />(let ((name1 value1)<br />      (name2 value2)<br />      name3<br />      name4<br />      (name5 value5)<br />      name6<br />      ...))</pre><br />Each <code>var-decl</code> is either a single name, or <em>(name initial-value)</em>.  You can mix initialized and uninitialized values in any order.  Uninitialized variables get the initial value <code>nil</code>.<br /><br />You can have multiple <code>let</code> clauses in a function.  Code written for performance often collects all declarations into a single <code>let</code> at the top, since it's a bit faster that way.  Typically you should write your code for clarity first.<br /><br /><b>reference parameters</b><br /><br />C++
 has reference parameters, which allow you to modify variables from the 
caller's stack.  Java does not, so you have to work around it 
occasionally by passing in a 1-element array, or using an instance 
variable, or whatever.<br /><br />Emacs Lisp does not have true 
reference parameters, but it has dynamic scope, which means you can 
modify values on your caller's stack anyway.  Consider the following 
pair of functions:<br /><pre>(defun foo ()<br />  (let ((x 6))  ; define a local (i.e., stack) variable x initialized to 6<br />    (bar)       ; call bar<br />    x))         ; return x<br /><br />(defun bar ()<br />  (setq x 7))   ; finds and modifies x in the caller's stack frame</pre><br />If you invoke <code>(foo)</code> the return value is 7.<br /><br />Dynamic
 scoping is generally considered a bad design bordering on evil, but it 
can occasionally come in handy.  If nothing else, it's good to know it's
 what Emacs does.<br /><br /><b>return</b><br /><br />A lisp function by
 default returns the value of the last expression executed in the 
function.  Sometimes it's possible to structure your function so that 
every possible return value is in a "tail position" (meaning the last 
expression out before the door closes, so to speak.)  For instance:<br /><table cellspacing="3" cellpadding="3" border="1"><br />  <tr>    <th>Emacs Lisp</th>    <th>JavaScript</th>  </tr><tr><td><pre>(require 'calendar)<br /><br />(defun day-name ()<br />  (let ((date (calendar-day-of-week<br />               (calendar-current-date))))<br />    (if (= date 0)<br />        "Sunday"<br />      (if (= date 6)<br />          "Saturday"<br />        "weekday"))))</pre></td><td><pre>function dayName() {<br />  var date = new Date().getDay();<br />  switch (date) {<br />    case 0:<br />      return "Sunday";<br />    case 6:<br />      return "Saturday";<br />    default:<br />      return "weekday";<br />  }<br />}</pre></td></tr></table><br />The return value is just the result of the last expression, so whatever our nested <code>if</code> produces is automatically returned, and there's no need here for an explicit <code>return</code> form.<br /><br />However, sometimes restructuring the function this way is inconvenient, and you'd prefer to do an "early return".<br /><br />You can do early returns in Emacs Lisp the same way you do <code>break</code> and <code>continue</code>, using the <code>catch/throw</code>
 facility.  Usually simple functions can be structured so you don't need
 this – it's most often useful for larger, deeply-nested functions.  So 
for a contrived example, we'll just rewrite the function above to be 
closer to the JavaScript version:<br /><pre>(defun day-name ()<br />  (let ((date (calendar-day-of-week<br />               (calendar-current-date))))  ; 0-6<br />    (catch 'return<br />      (case date<br />        (0<br />         (throw 'return "Sunday"))<br />        (6<br />         (throw 'return "Saturday"))<br />        (t<br />         (throw 'return "weekday"))))))</pre><br />Obviously using <code>catch/throw</code>
 here is slow and clunky compared to the alternatives, but sometimes 
it's exactly what you need to get out of a deeply nested construct.<br /><br /><b>try/catch</b><br /><br />We've already discussed <code>catch/throw</code>, an exception-like facility for normal control flow transfers.<br /><br />Emacs
 has a different facility for real error conditions, called the 
"conditions" system.  Going through the full system is out of scope for 
our primer, but I'll cover how to catch all exceptions and how to ignore
 (squelch) them.<br /><br />Here's an example of a universal try/catch using the <code>condition-case</code> construct, with a Java equivalent:<br /><br /><table cellspacing="3" cellpadding="3" border="1"><br />  <tr>    <th>Emacs Lisp</th>    <th>Java</th>  </tr><tr><td><pre>(condition-case nil<br />    (progn<br />      (do-something)<br />      (do-something-else))<br />  (error<br />   (message "oh no!")<br />   (do-recovery-stuff)))</pre></td><td><pre>try {<br />  doSomething();<br />  doSomethingElse();<br />} catch (Throwable t) {<br />  print("uh-oh");<br />  doRecoveryStuff();<br />}</pre></td></tr></table><br />If you want an empty catch block (just squelch the error), you can use <code>ignore-errors</code>:<br /><pre>(ignore-errors<br />  (do-something)<br />  (do-something-else))</pre><br />It's sometimes a good idea to slap an <code>ignore-errors</code>
 around bits of elisp code in your startup file that may not always 
work, so you can still at least start your Emacs up if the code is 
failing.<br /><br />The <code>condition-case nil</code> means "Don't 
assign the error to a named variable."  Elisp lets you catch different 
kinds of errors and examine the error data.  You can read the Emacs 
manual or Info pages to learn more about how to do that.<br /><br />The <code>progn</code> is necessary if you have multiple expressions (in C/Java, statements) to evaluate in the <code>condition-case</code> body.<br /><br /><code>condition-case</code> will not catch values thrown by <code>throw</code> – the two systems are independent.<br /><br /><b>try/finally</b><br /><br />Emacs has a "finally"-like facility called <code>unwind-protect</code>.<br /><br /><table cellspacing="3" cellpadding="3" border="1"><br />  <tr>    <th>Emacs Lisp</th>    <th>Java</th>  </tr><tr><td><pre>(unwind-protect<br />    (progn<br />      (do-something)<br />      (do-something-else))<br />  (first-finally-expr)<br />  (second-finally-expr))</pre></td><td><pre>try {<br />  doSomething();<br />  doSomethingElse();<br />} finally {<br />  firstFinallyExpr();<br />  secondFinallyExpr();<br />}</pre></td></tr></table><br />Like <code>condition-case</code>, <code>unwind-protect</code> takes a single <em>body-form</em> followed by one or more cleanup forms, so you need to use <code>progn</code> if you have more than one expression in the body.<br /><br /><b>try/catch/finally</b><br /><br />If you make the <code>condition-case</code> (which is basically <code>try/catch</code>) the body-form of an <code>unwind-protect</code> (which is basically <code>try/finally</code>), you get the effect of <code>try/catch/finally</code>:<br /><pre>(unwind-protect                 ; finally<br />    (condition-case nil         ; try<br />        (progn                  ; {<br />          (do-something)        ;   body-1<br />          (do-something-else))  ;   body-2 }<br />      (error                    ; catch<br />       (message "oh no!")       ; { catch 1<br />       (poop-pants)))           ;   catch 2 }<br />  (first-finally-expr)          ; { finally 1<br />  (second-finally-expr))        ;   finally 2 }</pre><h2>Classes</h2>Emacs
 Lisp is not object-oriented in the standard sense:  it doesn't have 
classes, inheritance, polymorphism and so on.  The Common Lisp package 
includes a useful feature called <code>defstruct</code> that gives you some simple OOP-like support.  I'll walk through a basic example.<br /><br />These two declarations are essentially equivalent:<br /><table cellspacing="3" cellpadding="3" border="1"><br />  <tr>    <th>Emacs Lisp</th>    <th>Java</th>  </tr><tr><td><pre>(require 'cl)  ; top of file  <br /><br />(defstruct person<br />  "A person structure."<br />  name<br />  (age 0)<br />  (height 0.0))</pre></td><td><pre>/* A Person class */<br />class Person {<br />  String name;<br />  int age;<br />  double height;<br />  public Person() {}<br />  public Person(String name) {<br />    this(name, 0, 0);<br />  }<br />  public Person(int age) {<br />    this(null, age, 0);<br />  }<br />  public Person(double height) {<br />    this(null, 0, height);<br />  }<br />  public Person(String name, int age) {<br />    this(name, age, 0);<br />  }<br />  public Person(String name, double height) {<br />    this(name, 0, height);<br />  }<br />  public Person(int age, double height) {<br />    this(null, age, height);<br />  }<br />  public Person(String name, int age, double height) {<br />    this.name = name;<br />    this.age = age;<br />    this.height = height;<br />  }<br />}</pre></td></tr></table><br />Both create a "class" with three named fields, and constructors for initializing any subset of the fields.  With <code>defstruct</code> you get one constructor with keyword parameters, so these are all valid:<br /><pre>(make-person)  ; new Person()<br />(make-person :age 39)  ; new Person(39)<br />(make-person :name "Steve" :height 5.83 :age 39)  ; new Person("Steve", 39, 5.83)</pre><br />The <code>defstruct</code> macro supports single-inheritance (to arbitrary depth):<br /><table cellspacing="3" cellpadding="3" border="1"><br />  <tr>    <th>Emacs Lisp</th>    <th>Java</th>  </tr><tr><td><pre>(defstruct (employee<br />            (:include person))<br />  "An employee structure."<br />  company<br />  (level 1)<br />  (title "n00b"))</pre></td><td><pre>/* An Employee class */<br />class Employee extends Person {<br />  String company;<br />  int level = 1;<br />  String title = "n00b";<br />  public Employee() {<br />  }<br />  public Employee(String name,<br />                  String company) {<br />    super(name);<br />    this.company = company;<br />  }<br />  public Employee(String name,<br />                  int age,<br />                  String company) {<br />    super(name, age);<br />    this.company = company;<br />  }<br />  public Employee(String name,<br />                  int age,<br />                  double height,<br />                  String company) {<br />    super(name, age, height);<br />    this.company = company;<br />  }<br />  public Employee(String name,<br />                  int age,<br />                  String company,<br />                  int level) {<br />    super(name, age);<br />    this.company = company;<br />    this.level = level;<br />  }<br />  public Employee(String name,<br />                  int age,<br />                  String co,<br />                  int lvl,<br />                  String title) {<br />    super(name, age);<br />    this.company = co;<br />    this.level = lvl;<br />    this.title = title;<br />  }<br />  // (remaining 150 overloaded constructors elided for brevity)<br />}</pre></td></tr></table><br />The <code>defstruct</code>
 macro provides a flexible default constructor, but also gives you a 
fair amount of control over your constructor(s) if you prefer.<br /><br />The <code>defstruct</code> macro creates an <code>instanceof</code>-like predicate function named after the struct, so you can say:<br /><pre>(person-p (make-person))<br />t<br />(employee-p (make-person))<br />nil<br />(employee-p (make-employee))<br />t<br />(person-p (make-employee))  ; yes, it inherits from person<br />t</pre>Java
 may suck at declaring constructors, but Emacs Lisp makes up for it by 
sucking at setting fields.  To set a field in a struct, you have to use 
the <code>setf</code> function, and construct the field name by prepending the structure name.  So:<br /><br /><table cellspacing="3" cellpadding="3" border="1"><br />  <tr>    <th>Emacs Lisp</th>    <th>Java</th>  </tr><tr><td><pre>(setq e (make-employee))<br />(setf (employee-name e) "Steve"<br />      (employee-age e) 39<br />      (employee-company e) "Google"<br />      (employee-title e) "Janitor")</pre></td><td><pre>Employee e = new Employee();<br />e.name = "Steve";<br />e.age = 39;<br />e.company = "Google";<br />e.title = "Janitor";</pre></td></tr></table><br />The Lisp one doesn't look too bad here, but in practice (because Elisp has no namespace support and no <code>with-slots</code> macro), you wind up with long structure and field names.  So your <code>defstruct</code>-enabled elisp code tends to look more like this:<br /><pre>(setf (js2-compiler-data-current-script-or-function compiler-data) current-script<br />      (js2-compiler-data-line-number compiler-data) current-line<br />      (js2-compiler-data-allow-member-expr-as-function-name compiler-data) allow<br />      (js2-compiler-data-language-version compiler-data) language-version)</pre>So it goes.<br /><br />To
 fetch the value of a field in a struct variable, you concatenate the 
struct name with the field name and use it as a function call:<br /><pre>(person-name steve)  ; yields "Steve"</pre> There's more that <code>defstruct</code> can do – it's a pretty decent facility, all things considered, though it falls well short of a full object system.<br /><br /><b>Buffers as classes</b><br /><br />In
 Elisp programming it can often be useful to think of buffers as 
instances of your own classes.  This is because Emacs supports the 
notion of buffer-local variables:  variables that automatically become 
buffer-local whenever they are set in any fashion.  They become part of 
the scope chain for any code executing in the buffer, so they act a lot 
like encapsulated instance variables.<br /><br />You can use the function <code>make-variable-buffer-local</code> to declare a variable as buffer-local.  Usually it comes right after the <code>defvar</code> or <code>defconst</code> declaration (see below.)<br /><h2>Variables</h2>You can declare a variable, optionally giving it some runtime documentation, with <code>defvar</code> or <code>defconst</code>:<br /><pre>(defconst pi 3.14159 "A gross approximation of pi.")</pre>The syntax is <code>(defvar <em>name</em> <em>value</em> [ <em>doc-string</em> ])</code>.<br /><br />Ironically, <code>defconst</code> is variable and <code>defvar</code> is constant, at least if you re-evaluate them.  To change the value of a <code>defvar</code> variable by re-evaluating its declaration you need to use <code>makunbound</code> to unbind it first.  You can always change the value of any <code>defvar</code> or <code>defconst</code> variable using <code>setq</code>.  The only difference between the two is that <code>defconst</code> makes it clearer to the programmer that the value is not intended to change.<br /><br />You can use <code>setq</code> to create brand-new variables, but if you use <code>defvar</code>, the byte-compiler will be able to catch more typos.<br /><h2>Further reading</h2>Emacs
 Lisp is a real programming language.  It has a compiler, a debugger, a 
profiler, pretty-printers, runtime documentation, libraries, I/O, 
networking, process control and much more.  There's a lot to learn, but 
I'm hoping this little primer has got you over the hump, as it were.<br /><br />In
 spite of its various quirks and annoyances, Elisp is reasonably fun to 
program in once you get the hang of it.  As a language it's not that 
great, and everyone wishes it were Common Lisp or Scheme or some other 
reasonable Lisp dialect.  Some people even wish it weren't Lisp at all, 
if you can believe that!  (hee)<br /><br />But it's really, really 
useful to be able to customize your editor, and also to be able to fix 
problems with elisp code you borrowed or inherited.  So a little Elisp 
goes a long way.<br /><br />For those of you learning Emacs Lisp, please
 let me know if you found this useful.  If you try writing some Emacs 
extensions, let me know what you would like to see documented next; I 
can always do another installment of the Emergency Elisp series if 
there's enough interest.<br /><br />Good luck!
</body>
</html>
